﻿using UnityEngine;
using System.Collections;
using BehaviorDesigner.Runtime;
using BehaviorDesigner.Runtime.Tasks;

public class Defense : Action {

    public SharedFloat viewDistance;
    public SharedFloat fieldOfViewAngle;
    public SharedFloat speed;
    public SharedFloat angularSpeed;
    public SharedTransform target;//防御目标

    private float sqrtViewDistance;
    private NavMeshAgent navMeshAgent;

    public override void OnAwake()
    {
        navMeshAgent = this.GetComponent<NavMeshAgent>();

    }
    public override void OnStart()
    {
        sqrtViewDistance = viewDistance.Value * viewDistance.Value;
        navMeshAgent.enabled = true;
        navMeshAgent.speed = speed.Value;
        navMeshAgent.angularSpeed = angularSpeed.Value;
        navMeshAgent.destination = target.Value.position;
    }
    public override void OnEnd()
    {
        navMeshAgent.enabled = false;
    }

    public override TaskStatus OnUpdate()
    {
        if (target == null || target.Value == null) {
            return TaskStatus.Failure;
        }

        float sqrtDis = (target.Value.position - transform.position).magnitude;
        float angle = Vector3.Angle(transform.forward, target.Value.position - transform.position);

        if (sqrtDis < sqrtViewDistance && angle < fieldOfViewAngle.Value * 0.5) {
            if (navMeshAgent.destination != target.Value.position) {
                navMeshAgent.destination = target.Value.position;
            }
            return TaskStatus.Running;
        }
        else{
            return TaskStatus.Success;
        }
    }
}
